<?php
namespace Addons\QyWechat\Controller\Admin;

use Models\BaseModel as Model;
use Session;
use Addons\QyWechat\Helper;
use Lib\Request;
use Addons\QyWechat\Config\app;
use Addons\QyWechat\Config\rbacAuth;

class Rbac extends BaseAdmin
{	
	/**
	*  显示页面 
	**/
    public function index(){
		$wid = Session::get('wid');
		
		return $this->show();
	}
	/**
	*  角色列表
	**/
	public function role(){
		$wid = $this->wid;
		setApi();
		$roles = (new Model('qy_rbac_role'))->field('role_name,type')->where(['wid'=>$wid])->list_all_array();
		if(count($roles) < 1){
			$auth_3 = json_encode(['cuscontact_customerlist'=>1,'cuscontact_clmanage'=>1],320);
			$auth_4 = json_encode(['cuscontact_customerlist'=>3,'cuscontact_clmanage'=>3],320);
			$sql = "INSERT INTO qvmh_qy_rbac_role (wid,role_name,auth,menu,type) values ($wid,'超级管理员',null,null,1),($wid,'管理员',null,null,2),($wid,'部门管理员','$auth_3',null,3),($wid,'普通员工','$auth_4',null,4)";
			db_query($sql);
			$roles = (new Model('qy_rbac_role'))->field('role_name,type')->where(['wid'=>$wid])->list_all_array();
		}
		sendSuccess('角色列表',$roles);
	}
	/**
	*  权限列表
	**/
	// public function auth(){
	// 	$wid = $this->wid;
	// 	setApi();
	// 	$where = [];
	// 	$where['pid'] = 0;
	// 	$type = $_POST['type'] ?: 3;
	// 	$res = [];
	// 	$role_auth_arr = [];

	// 	$auths = (new Model('qy_rbac_auth'))->where(['pid'=>0,'type'=>$type])->list_all_array();
	// 	$role_auth = (new Model('qy_rbac_role'))->find(['wid'=>$wid,'type'=>$type]);
	// 	$role_auth_arr = json_decode($role_auth->auth,1);

	// 	foreach ($auths as $key => $auth) {
	// 		$res[$auth['auth'].'_data'][$auth['auth']] = (new Model('qy_rbac_auth'))->field('id,auth_name')->where(['pid'=>$auth['id']])->list_all_array();
	// 		foreach ($res[$auth['auth'].'_data'][$auth['auth']] as $k => $val) {
	// 			if($val['id'] == $role_auth_arr[$auth['auth']]){
	// 				$res[$auth['auth'].'_data'][$auth['auth']][$k]['is_auth'] = true;
	// 				$res[$auth['auth'].'_data'][$auth['auth'].'_selected'] = $val['auth_name'];
	// 			}else{
	// 				$res[$auth['auth'].'_data'][$auth['auth']][$k]['is_auth'] = false;
	// 			}
	// 		}
	// 	}
	// 	sendSuccess('权限列表',$res);
	// }
	/**
	*  权限列表
	**/
	public function auth(){
		$wid = $this->wid;
		setApi();
		$pub = (new Model('pubs'))->find($wid);
		$user = (new Model('user'))->find($pub->uid);
		$auth_check = (new Model('auth_check'))->find(['auth_id'=>$user->level_id]);
		$nopages = explode(',',$auth_check->controllers);
		$type = $_POST['type']?:2;
		$rbac_role = (new Model('qy_rbac_role'))->find(['wid'=>$wid,'type'=>$type]);
		$allow_menu = explode(',',$rbac_role->menu);
		$auth = [];
		$rbac = [];
		switch ($type) {
			case 3:
				$rbac = rbacAuth::$rbac_3;
				$auth = json_decode($rbac_role->auth,1);
				break;
			case 4:
				$rbac = rbacAuth::$rbac_4;
				$auth = json_decode($rbac_role->auth,1);
				break;
			default:
				$rbac = rbacAuth::$rbac_2;
				break;
		}
		$data = [];
		include DOXCX_FRAME_PATH.'controller'.DS.'admin'.DS.'index.php';
		foreach($index as $key=>$value1){
			$datatwo = [];
			$datatwo['name'] = $value1['name'];
			$datatwo['sub'] = [];
			foreach($value1['sub'] as $key1=>$value2){
				if(!in_array($value2['file'], $nopages)){
					$is_auth = $type > 2 ? in_array($value2['file'], $allow_menu) ? true : false : true;
					$optional = $type > 2 ? is_array($rbac[$value2['file']]) ? true : false : false;
					$optional_data = []; 
					$selected = $optional ? array_key_exists($rbac[$value2['file']][0], $auth) ?  $rbac[$value2['file']][1][$auth[$rbac[$value2['file']][0]]] : $rbac[$value2['file']][1][1] : '';
					if($optional){
						foreach ($rbac[$value2['file']][1] as $id => $selectname) {
							$optional_data[] = [
								'id' => $id,
								'name' => $selectname,
								'file' => $value2['file']
							];
						}
					}
					$datatwo['sub'][] = [
						'name' => $value2['name'],
						'file' => $value2['file'],
						'file' => $value2['file'],
						'is_auth' => $is_auth,
						'optional' => $optional,
						'selected' => $selected,
						'optional_data' => $optional_data,
						'optional_describe' => $optional ? '' : $rbac[$value2['file']]
					];
				}
			}
			
			if(count($datatwo['sub'])>0){
				$data[] = $datatwo;
			}		
			
		}
		sendSuccess('权限列表',$data);
	}
	/**
	*  用户角色列表
	**/
	public function user_role_list(){
		$wid = $this->wid;
		setApi();
		$pageIndex = $_POST['page'] ?: 1;
		$pageSize = $_POST['pageSize'] ?: 10;
		$limit = $pageSize*($pageIndex-1).','.$pageSize;
		$type = $_POST['type']?:1;
		$where = [];
		$where['wid'] = $wid;
		$where['type'] = $type;
		$name = $_POST['name'];
		$count = 0;
		// $qyUser = (new Model('qy_user_list'))->field('id,wid,name,department,department_name');
		switch ($type) {
			case 1:
				$pub = (new Model('pubs'))->find($wid);
				$user = (new Model('user'))->find($pub->uid);
				$res = [
					[
						'id' => 0,
						'wid' => $wid,
						'name' => $user->un,
						'department' => [],
						'department_name' => [],
						'manage_department_name' => ['全部部门']
					]
				];
				$count = count($res);
				// sendSuccess('超级管理员',$res);
				sendResponse(['status' => 'success', 'msg' => '超级管理员', 'data' => $res, 'count'=>$count], true);
				break; 
			case 2:   //管理员
				if($name){
					$nameIdArr = array_column((new Model('qy_user_list'))->field('id')->where(['wid'=>$wid,'name@~'=>$name])->list_all_array(),'id');
					$idArr = array_column((new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>2,'user_id'=>$nameIdArr])->limit($limit)->list_all_array(), 'user_id');
					$count = (new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>2,'user_id'=>$nameIdArr])->count();
				}else{
					$idArr = array_column((new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>2])->limit($limit)->list_all_array(), 'user_id');
					$count = (new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>2])->count();
				}
				
				$qyUser = (new Model('qy_user_list'))->field('id,wid,name,department,department_name')->where(['id'=>$idArr])->list_all_array();
				foreach ($qyUser as $k => $user) {
					$qyUser[$k]['department'] = json_decode($user['department'],1);
					$qyUser[$k]['department_name'] = implode(",", json_decode($user['department_name'],1));
					$qyUser[$k]['manage_department_name'] = ['全部部门'];
				}
				// sendSuccess('管理员',$qyUser);
				sendResponse(['status' => 'success', 'msg' => '管理员', 'data' => $qyUser, 'count'=>$count], true);
				break;
			case 3:  //部门管理员
				if($name){
					$nameIdArr = array_column((new Model('qy_user_list'))->field('id')->where(['wid'=>$wid,'name@~'=>$name])->list_all_array(),'id');
					$idArr = array_column((new Model('qy_rbac_role_user'))->where(['wid'=>$wid,'type'=>3,'user_id'=>$nameIdArr])->limit($limit)->list_all_array(), 'user_id');
					$count = (new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>3,'user_id'=>$nameIdArr])->count();
				}else{
					$idArr = array_column((new Model('qy_rbac_role_user'))->where(['wid'=>$wid,'type'=>3])->limit($limit)->list_all_array(), 'user_id');
					$count = (new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>3])->count();
				}
				
				$qyUser = (new Model('qy_user_list'))->field('id,wid,name,department,department_name')->where(['id'=>$idArr])->list_all_array();
				$manage_department_name_arr = array_column((new Model('qy_department_list'))->where(['wid'=>$wid])->list_all_array(), 'department_name','department_id');
				foreach ($qyUser as $k => $user) {
					$qyUser[$k]['department'] = json_decode($user['department'],1);
					$qyUser[$k]['department_name'] = implode(",", json_decode($user['department_name'],1));
					$role_user = (new Model('qy_rbac_role_user'))->find(['wid'=>$wid,'user_id'=>$user['id']]);
					$manage_department_name = [];
					$manage_department_name_id = json_decode($role_user->department_id,1);
					foreach ($manage_department_name_id as  $department_id) {
						$manage_department_name[] = $manage_department_name_arr[$department_id];
					}
					$qyUser[$k]['manage_department_name'] = $manage_department_name;
				}
				// sendSuccess('部门管理员',$qyUser);
				sendResponse(['status' => 'success', 'msg' => '部门管理员', 'data' => $qyUser, 'count'=>$count], true);
				break;
			case 4:
				$idArr = array_column((new Model('qy_rbac_role_user'))->where(['wid'=>$wid])->list_all_array(), 'user_id');
				$idString = implode(',', $idArr);

				$sql = "select id,name,department,department_name from qvmh_qy_user_list where wid = {$wid} and status != 5 and is_del != 1";
				if($idString){
					$sql .= " and id not in ($idString)";
				}
				if($name){
					$sql .= " and name like '%{$name}%'";
				}
				$count = count(db_query($sql));
				$sql .= " limit {$limit}";
				$qyUser = db_query($sql);
				foreach ($qyUser as $k => $user) {
					$qyUser[$k]['department'] = json_decode($user['department'],1);
					$qyUser[$k]['department_name'] = implode(",", json_decode($user['department_name'],1));
					$qyUser[$k]['manage_department_name'] = '-';
				}
				// sendSuccess('普通员工',$qyUser);
				sendResponse(['status' => 'success', 'msg' => '普通员工', 'data' => $qyUser, 'count'=>$count], true);
				break;
			default:
				# code...
				break;
		}
	}
	/**
	* 弹框用户列表
	**/
	public function pop_user_role_list(){
		$wid = $this->wid;
		setApi();
		$pageIndex = $_POST['page'] ?: 1;
		$pageSize = $_POST['pageSize'] ?: 10;
		$limit = $pageSize*($pageIndex-1).','.$pageSize;
		$type = $_POST['type']?:2;
		$where = [];
		$where['wid'] = $wid;
		$where['type'] = $type;
		$name = $_POST['name'];
		$count = 0;
		$role_name_arr = array_column((new Model('qy_rbac_role'))->field('role_name,type')->where(['wid'=>$wid])->list_all_array(), 'role_name','type');
		switch ($type) {
			case 1:
				break; 
			case 2:   //管理员
				$idArr = array_column((new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>2])->list_all_array(), 'user_id');
				$idString = implode(',', $idArr);
				$sql = "select id,name,department from qvmh_qy_user_list where wid = {$wid} and status != 5 and is_del != 1";
				if($idString){
					$sql .= " and id not in ($idString)";
				}
				if($name){
					$sql .= " and name like '%{$name}%'";
				}
				$count = count(db_query($sql));
				$sql .= " limit {$limit}";
				$qyUser = db_query($sql);
				foreach ($qyUser as $k => $user) {
					$user_role = (new Model('qy_rbac_role_user'))->find(['wid'=>$wid,'user_id'=>$user['id']]);
					if($user_role->id){
						$qyUser[$k]['type'] = $user_role->type;
						$qyUser[$k]['roleName'] = $role_name_arr[$user_role->type];
					}else{
						$qyUser[$k]['type'] = 4;
						$qyUser[$k]['roleName'] = '普通员工';
					}
					$qyUser[$k]['department'] = json_decode( $user['department'],1);
				}
				// sendSuccess('添加管理员弹框用户列表',$qyUser);
				sendResponse(['status' => 'success', 'msg' => '添加管理员弹框用户列表', 'data' => $qyUser, 'count'=>$count], true);
				break;
			case 3:  //部门管理员
				$idArr = array_column((new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid,'type'=>3])->list_all_array(), 'user_id');
				$idString = implode(',', $idArr);
				$sql = "select id,name,department from qvmh_qy_user_list where wid = {$wid} and status != 5 and is_del != 1";
				if($idString){
					$sql .= " and id not in ($idString)";
				}
				if($name){
					$sql .= " and name like '%{$name}%'";
				}
				$count = count(db_query($sql));
				$sql .= " limit {$limit}";
				$qyUser = db_query($sql);
				foreach ($qyUser as $k => $user) {
					$user_role = (new Model('qy_rbac_role_user'))->find(['wid'=>$wid,'user_id'=>$user['id']]);
					if($user_role->id){
						$qyUser[$k]['type'] = $user_role->type;
						$qyUser[$k]['roleName'] = $role_name_arr[$user_role->type];
					}else{
						$qyUser[$k]['type'] = 4;
						$qyUser[$k]['roleName'] = '普通员工';
					}
					$qyUser[$k]['department'] = json_decode( $user['department'],1);
				}
				// sendSuccess('添加部门理员弹框用户列表',$qyUser);
				sendResponse(['status' => 'success', 'msg' => '添加部门理员弹框用户列表', 'data' => $qyUser, 'count'=>$count], true);
				break;
			case 4:
				$idArr = array_column((new Model('qy_rbac_role_user'))->field('user_id')->where(['wid'=>$wid])->list_all_array(), 'user_id');
				if($name){
					$qyUser = (new Model('qy_user_list'))->field('id,name,department')->where(['wid'=>$wid,'id'=>$idArr,'name@~'=>$name])->limit($limit)->list_all_array();
					$count = (new Model('qy_user_list'))->field('id')->where(['wid'=>$wid,'id'=>$idArr,'name@~'=>$name])->count();
				}else{
					$qyUser = (new Model('qy_user_list'))->field('id,name,department')->where(['wid'=>$wid,'id'=>$idArr])->limit($limit)->list_all_array();
					$count = count($idArr);
				}
				
				foreach ($qyUser as $k => $user) {
					$user_role = (new Model('qy_rbac_role_user'))->find(['wid'=>$wid,'user_id'=>$user['id']]);
					$qyUser[$k]['type'] = $user_role->type;
					$qyUser[$k]['roleName'] = $role_name_arr[$user_role->type];
					$qyUser[$k]['department'] = json_decode( $user['department'],1);
				}
				// sendSuccess('添加普通员工弹框用户列表',$qyUser);
				sendResponse(['status' => 'success', 'msg' => '添加普通员工弹框用户列表', 'data' => $qyUser, 'count'=>$count], true);
				break;
			default:
				# code...
				break;
		}
	}
	/**
	*  更改用户角色
	**/
	public function update_user_role(){
		$wid = $this->wid;
		setApi();
		$idArr = $_POST['id'];
		$type = $_POST['type'];
		if(!$idArr){
			sendError('请选择用户');
		}
		if(!$type){
			sendError('请选择角色类型');
		}
		switch ($type) {
			case 1:
				sendError('不可更改角色类型');
				break;
			case 2:
				foreach ($idArr as  $id) {
					$role_user = (new Model('qy_rbac_role_user'))->find(['wid'=>$wid,'user_id'=>$id]);
					if(!$role_user->id){
						$role_user = new Model('qy_rbac_role_user');
						$role_user->wid = $wid;
						$role_user->user_id = $id;
					}
					$role_user->type = 2;
					if($role_user->save()){
						$recode = new Model('qy_rbac_record');
						$recode->wid = $wid;
						$recode->type = 1;
						$recode->role_type = 2;
						$recode->user_id = $id;
						$recode->inputer_id = 0;
						$recode->ctime = time();
						$recode->save();
					}
				}
				sendSuccess('修改角色成功');
				break;
			case 3:
				$department_id = $_POST['department_id'] ? json_encode($_POST['department_id'],320) : '';
				foreach ($idArr as  $id) {
					$role_user = (new Model('qy_rbac_role_user'))->find(['wid'=>$wid,'user_id'=>$id]);
					if(!$role_user->id){
						$role_user = new Model('qy_rbac_role_user');
						$role_user->wid = $wid;
						$role_user->user_id = $id;
					}
					$role_user->type = 3;	
					if(!$department_id){
						$qYuser = (new Model('qy_user_list'))->find($id);
						$department_id = $qYuser->department;
					}
					$role_user->department_id = $department_id;
					if($role_user->save()){
						$recode = new Model('qy_rbac_record');
						$recode->wid = $wid;
						$recode->type = 1;
						$recode->role_type = 3;
						$recode->user_id = $id;
						$recode->inputer_id = 0;
						$recode->ctime = time();
						$recode->save();
					}
				}
				sendSuccess('修改角色成功');
				break;
			case 4:
				foreach ($idArr as  $id) {
					$role_user = (new Model('qy_rbac_role_user'))->find(['wid'=>$wid,'user_id'=>$id]);
					if($role_user->id){
						if($role_user->remove()){
							$recode = new Model('qy_rbac_record');
							$recode->wid = $wid;
							$recode->type = 1;
							$recode->role_type = 4;
							$recode->user_id = $id;
							$recode->inputer_id = 0;
							$recode->ctime = time();
							$recode->save();
						}
					}
				}
				sendSuccess('修改角色成功');
				break;
			default:
				# code...
				break;
		}
	}
	/**
	*  操作记录
	**/
	public function record(){
		setApi();
		$wid = $this->wid;
		$pageIndex = $_POST['page'] ?: 1;
		$pageSize = $_POST['pageSize'] ?: 10;
		$limit = $pageSize*($pageIndex-1).','.$pageSize;
		$records = (new Model('qy_rbac_record'))->where(['wid'=>$wid])->order('id desc')->limit($limit)->list_all_array();
		$pub = (new Model('pubs'))->find($wid);
		$user = (new Model('user'))->find($pub->uid);
		$role = array_column((new Model('qy_rbac_role'))->where(['wid'=>$wid])->list_all_array(), 'role_name','type');
		$res = [];
		foreach ($records as  $record) {
			if($record['inputer_id'] == 0){
				$inputer = "超级管理员".$user->un;
				$avatar = 'http://weidogstest.oss-cn-beijing.aliyuncs.com/b77a7477fa0143d0280ef2dbebb533bf.gif';
			}else{
				$qyUser = (new Model('qy_user_list'))->find($record['inputer_id']);
				if(!$qyUser->id) continue;
				$inputer = $qyUser->name;	
				$avatar = $qyUser->avatar;
			}
			$qyUserName = '';
			$update_auth_name = '';
			$update_auth_zi_name = '';
			$oper_record = '';
			switch ($record['type']) {
				case 1:
					$qyUserBy = (new Model('qy_user_list'))->find($record['user_id']);
					$qyUserName = $qyUserBy->name;
					$oper_record = $inputer.'将'.$qyUserName.'设为了'.$role[$record['role_type']];
					break;
				case 2:
					$auth = json_decode($record['auth'],1);
					$menu_name = array_keys($auth); 
					$oper_record = $inputer.'将角色【'.$role[$record['role_type']].'】的'.'【'.$menu_name[0].'】的权限修改为【'.$auth[$menu_name[0]].'】';
					break;
				case 3:
					$auth = json_decode($record['auth'],1);
					$menu_name = array_keys($auth);
					$status = $auth[$menu_name] == 1 ? '开启' : '关闭';
					$oper_record = $inputer.$status.'了角色【'.$role[$record['role_type']].'】的【'.$menu_name[0].'】的菜单权限';
					break;
				default:
					# code...
					break;
			}
			$res[] = [
				'ctime'  => date('Y-m-d H:i:s',$record["ctime"]),
				'avatar' => $avatar,
				'record' => $oper_record,
			];
		}
		sendSuccess('操作记录',$res);
	}
	/**
	*  更改角色菜单权限
	**/
	public function update_role_menu_auth(){
		$wid = $wid = $this->wid;
		setApi();
		$type = $_POST['type'];
		if(!$type){
			sendError('请选择角色');
		}
		if(!isset($_POST['status'])){
			sendError('确实status参数');
		}
		switch ($type) {
			case 3:
				$rbac = rbacAuth::$rbac_3;
				break;
			case 4:
				$rbac = rbacAuth::$rbac_4;
				break;
			default:
				sendError('此角色不可更改菜单权限');
				break;
		}
		$role = (new Model('qy_rbac_role'))->find(['wid'=>$wid,'type'=>$type]);
		$menu_auth = explode(',', $role->menu);
		if($_POST['status'] == 1){
			array_push($menu_auth,$_POST['menulink']);
		}else{
			$key = array_search($_POST['menulink'], $menu_auth);
			if($key !== false){
				unset($menu_auth[$key]);
			}

		}

		$role->menu = implode(',', array_unique(array_filter($menu_auth)));
		if($role->save()){
			$recode = new Model('qy_rbac_record');
			$recode->wid = $wid;
			$recode->role_type = $type;
			$recode->type = 3;
			$recode->auth = json_encode([$_POST['name']=>$_POST['status']],320);
			$recode->inputer_id = 0;
			$recode->ctime = time();
			$recode->save();
			sendSuccess('操作成功');
		}
		sendError('操作失败');
	}
	/**
	*  更改角色权限
	**/
	public function update_role_auth(){
		$wid = $wid = $this->wid;
		setApi();
		$type = $_POST['type'];
		if(!$type){
			sendError('请选择角色');
		}
		switch ($type) {
			case 3:
				$rbac = rbacAuth::$rbac_3;
				break;
			case 4:
				$rbac = rbacAuth::$rbac_4;
				break;
			default:
				sendError('此角色不可更改菜单权限');
				break;
		}
		if(!$_POST['authflag']){
			sendError('请选择权限');
		}
		$role = (new Model('qy_rbac_role'))->find(['wid'=>$wid,'type'=>$type]);
		$auth = json_decode($role->auth,1);
		$auth[$rbac[$_POST['menulink']][0]] = $_POST['authflag'];
		$role->auth = json_encode($auth,320);
		if($role->save()){
			$recode = new Model('qy_rbac_record');
			$recode->wid = $wid;
			$recode->role_type = $type;
			$recode->type = 2;
			$recode->auth = json_encode([$_POST['name']=>$rbac[$_POST['menulink']][1][$_POST['authflag']]],320);
			$recode->inputer_id = 0;
			$recode->ctime = time();
			$recode->save();
			sendSuccess('操作成功');
		}
		sendError('操作失败');
	}
	/**
	*  部门列表
	**/
	public function department_list(){
		$wid = $this->wid;
		setApi();
		$department_list = (new Model('qy_department_list'))->field('department_id,department_name,department_parentid')->where(['wid'=>$wid])->list_all_array();
		$res = $this->get_department_list($department_list);
		sendSuccess('部门列表',$res);
	}

	public function get_department_list($list,$pid = 0){
		$res = [];
		$pid_list = array_column($list, 'department_parentid');
		foreach ($list as $val) {
			if($val['department_parentid'] == $pid){
				$down_res = array_key_exists($val['department_id'], $pid_list) ? true : false;
				$down_list = [];
				if($down_res){
					$down_list = $this->get_department_list($list,$val['department_id']);
				}
				$res[] = [
					'department_id' => $val['department_id'],
					'department_name' => $val['department_name'],
					'selected' => false,
					'hasMore' => $down_res,
					'nextData' => $down_list
				];
			}
		}
		return $res;
	}

}